﻿

using System;
using System.IO.Ports;

namespace CCSFeederCameraUI2.Services
{
    public class Scanner : IScanner
    {
        private SerialPort serialPort = new SerialPort();

        public ScannerReceiveData<byte[], uint> RxDataInd { get; set; }

        public bool OpenPort(string _portName)
        {
            try
            {
                if (this.serialPort.IsOpen)
                {
                    Console.WriteLine($"扫码枪串口{_portName}已打开");
                    return false;
                }
                else
                {
                   
                    this.serialPort.PortName = _portName;
                    this.serialPort.Open();
                    this.serialPort.DiscardInBuffer();
                    this.serialPort.DiscardOutBuffer();
                    this.serialPort.WriteTimeout = 5000;
                    this.serialPort.ReadTimeout = 5000;
                    return true;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return false;
        }
        public Scanner()
        {
            this.serialPort.BaudRate = 9600;
            this.serialPort.Parity = Parity.None;
            this.serialPort.DataBits = 8;
            this.serialPort.StopBits = StopBits.One;
            this.serialPort.DataReceived += serialPort_DataReceived;
        }
        private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                int bytesToRead = this.serialPort.BytesToRead;
                byte[] array = new byte[bytesToRead];
                this.serialPort.Read(array, 0, bytesToRead);
                if (this.RxDataInd != null)
                {
                    this.RxDataInd(array, (uint)array.Length);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}
